@echo off
:: Windows CMD 贪吃蛇 - 单文件零依赖
:: 作者：CMDer
setlocal enabledelayedexpansion

:: 地图大小
set /a W=30,H=20,AREA=W*H

:: 初始化空地图
(for /l %%i in (0,1,%AREA%) do echo 0)>".\_map.tmp"

:: 蛇初始坐标（水平 5 节）
set /a x=5,y=H/2
(for %%i in (4 3 2 1 0) do echo !x! !y!&&set /a x-=1)>".\_snake.tmp"

:: 食物 & 分数
call :placeFood
set /a score=0

:: 初始方向（右）
set dirX=1&set dirY=0

:: 游戏主循环
:start
:: 1. 读当前输入（非阻塞）
choice /c wasdq /n /t 1 /d w >nul
if errorlevel 5 (echo 退出&del ".\_*.tmp"&exit /b)
if errorlevel 4 (set /a "dy=-1,dx=0"&goto move)
if errorlevel 3 (set /a "dy=1,dx=0"&goto move)
if errorlevel 2 (set /a "dx=-1,dy=0"&goto move)
if errorlevel 1 (set /a "dx=1,dy=0"&goto move)

:move
:: 2. 计算新头
set /a "headX=px+dx,headY=py+dy"
if %headX% LSS 0 set /a headX=W-1
if %headX% GEQ %W% set /a headX=0
if %headY% LSS 0 set /a headY=H-1
if %headY% GEQ %H% set /a headY=0

:: 3. 读食物坐标
for /f "tokens=1,2" %%a in ('type ".\_food.tmp"') do set fx=%%a&set fy=%%b

:: 4. 撞自己检测
findstr "!headX! !headY!" ".\_snake.tmp">nul && (echo Game Over! Score=%score%&del ".\_*.tmp"&pause&exit /b)

:: 5. 吃食物判断
set grow=0
if "!headX! !headY!"=="!fx! !fy!" (set /a grow=1,score+=1&call :placeFood)

:: 6. 把新头写进蛇文件
echo !headX! !headY!>>".\_snake.tmp"
if !grow!==0 (
  more +1 ".\_snake.tmp">".\_snake.tmp.new"
  move /y ".\_snake.tmp.new" ".\_snake.tmp">nul
)

:: 7. 更新当前头坐标（供下轮使用）
set px=!headX!&set py=!headY!

:: 8. 重绘屏幕
cls
echo Score: %score%   控制:WASD  退出:Q
echo+
type ".\_map.tmp"|repl "\x30" " " >".\_screen.tmp"
for /f "tokens=1,2" %%a in ('type ".\_snake.tmp"') do (
  set /a "pos=%%b*W+%%a+1"
  (for /f "tokens=1* delims=:" %%p in ('findstr /n "^" ".\_screen.tmp"') do (
    if %%p equ !pos! (echo %%bÛ) else (echo %%b)
  ))>".\_screen.new"
  move /y ".\_screen.new" ".\_screen.tmp">nul
)
for /f "delims=" %%l in ('type ".\_screen.tmp"') do echo %%l
goto start

:placeFood
set /a fx=!random! %% W, fy=!random! %% H
findstr "%fx% %fy%" ".\_snake.tmp">nul && goto placeFood
echo %fx% %fy%>".\_food.tmp"
set px=%fx%&set py=%fy%
goto :eof
